// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const $ = _.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  let month = event.month || 202105,
  skip = event.skip || 0,
  limit = event.limit || 20;
  return await db.collection('ad_idol').aggregate()
      .lookup({
      from: "ad_rank_month",
      let: {
        idol_id: '$_id',
      },
      pipeline: $.pipeline()
        .match(_.expr($.and([
          $.eq(['$idol_id', '$$idol_id']),
          $.eq(['$month', month])
        ])))
        .project({
          _id: 0,
          month: 1,
          votes: 1
        })
        .done(),
      as: 'rank',
    })
    .sort({
      "rank.votes": -1
    })
    .unwind({
      path: '$rank',
      preserveNullAndEmptyArrays: true
    })
    .skip(skip)
    .limit(limit)
    .end()
}